package com.znz.analysis.util;

import java.util.Date;

import javax.annotation.Resource;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Component;

import com.znz.analysis.constant.JwtConstant;
import com.znz.analysis.constant.properties.ExternalInterfaceProperties;

import org.apache.commons.codec.binary.Base64;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * @author 作者 :TP
 * @version 创建时间：2017年7月27日 上午10:35:56
 *
 */
@Component
public class JwtUtil {

	@Resource
	private ExternalInterfaceProperties apolloProperties;

	/**
	 * 由字符串生成加密key
	 * 
	 * @return
	 */
	private SecretKey generalKey() {
		String stringKey = JwtConstant.JWT_SECRET;
		byte[] encodedKey = Base64.decodeBase64(stringKey);
		SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
		return key;
	}

	/**
	 * 创建jwt
	 * 
	 * @param id
	 * @param subject
	 * @param ttlMillis
	 * @return
	 * @throws Exception
	 */
	public String createJWT(String id, String subject, long ttlMillis) {
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		SecretKey key = generalKey();
		JwtBuilder builder = Jwts.builder().setId(id).setIssuedAt(now).setSubject(subject).signWith(signatureAlgorithm,
				key);
		if (ttlMillis >= 0) {
			long expMillis = nowMillis + ttlMillis;
			Date exp = new Date(expMillis);
			builder.setExpiration(exp);
		}
		return builder.compact();
	}

	/**
	 * 解密jwt
	 * 
	 * @param jwt
	 * @return
	 * @throws Exception
	 */
	public Claims parseJWT(String jwt) throws Exception {
		SecretKey key = generalKey();
		Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
		return claims;
	}

	/**
	 * 生成subject信息
	 * 
	 * @param user
	 * @return
	 */
	public String generalSubject(String secretkey, String username, String pwd) {
		JSONObject jo = new JSONObject();
		jo.put("secretkey", secretkey);
		jo.put("username", username);
		jo.put("pwd", pwd);
		return jo.toString();
	}

}
